package com.indexingsystem.system.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.indexingsystem.boss.Vo.TablesQueryVo;
import com.indexingsystem.boss.Vo.TablesVo;
import com.indexingsystem.boss.admin.mapper.TablesColRelationsMapper;
import com.indexingsystem.boss.admin.mapper.TablesMapper;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.entity.Tables;
import com.indexingsystem.boss.entity.TablesColRelations;
import com.indexingsystem.boss.utils.BeanUtils;
import com.indexingsystem.boss.utils.TablesUtils;
import com.indexingsystem.system.service.ITablesService;

@Service
public class TablesServiceImpl implements ITablesService{
	
	@Resource
	private TablesMapper tablesMapper;
	
	@Resource
	private TablesColRelationsMapper tablesColRelationsMapper;

	@Override
	public int deleteByPrimaryKey(String tableId) {
		return tablesMapper.deleteByPrimaryKey(tableId);
	}

	@Override
	public int insert(Tables record) {
		return tablesMapper.insert(record);
	}

	@Override
	public int insertSelective(Tables record) {
		return tablesMapper.insertSelective(record);
	}

	@Override
	public Tables selectByPrimaryKey(String tableId) {
		return tablesMapper.selectByPrimaryKey(tableId);
	}

	@Override
	public int updateByPrimaryKeySelective(Tables record) {
		return tablesMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Tables record) {
		return tablesMapper.updateByPrimaryKey(record);
	}

	@Override
	public PagedResult<TablesQueryVo> getTablesList(TablesQueryVo tablesQueryVo) {
		Integer pageNo = tablesQueryVo.getPageNumber() == null ? 1 : tablesQueryVo.getPageNumber();
		Integer pageSize = tablesQueryVo.getPageSize() == null ? 10 : tablesQueryVo.getPageSize();
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage(pageNo, pageSize);
		return BeanUtils.toPagedResult(tablesMapper.getTablesList(tablesQueryVo));
	}

	@Override
	public Integer getTablesListCount(TablesQueryVo tablesQueryVo) {
		return tablesMapper.getTablesListCount(tablesQueryVo);
	}

	@Override
	public Integer deleteBatchTable(List<String> list) throws Exception{
		int result = 0;
		TablesVo tablesVo = null;
		for (String tableId : list) {
			tablesVo = new TablesVo();
			Tables tables = tablesMapper.selectByPrimaryKey(tableId);
			List<TablesColRelations> tablesColRelations = tablesColRelationsMapper.getTablesColRelationsByTables(tableId);
			tablesVo.setTables(tables);
			tablesVo.setTablesColRelations(tablesColRelations);
		  	TablesUtils.dropTable(tables.getTableName());
		}
		result = tablesMapper.batchDelectTable(list);
		tablesColRelationsMapper.batchDelectTableColRelations(list);
		return result;
	}

	@Override
	public int createTable(TablesVo tablesVo)throws Exception{
	    int value= 0;
		if(null != tablesVo){
			List<TablesColRelations> list = tablesVo.getTablesColRelations();
			if(null != list && list.size()>0){
				for (TablesColRelations tables:list) {
					tablesColRelationsMapper.insertSelective(tables);
				}
				value = tablesMapper.insertSelective(tablesVo.getTables());
				int objVal = createTableSql(tablesVo);
				if(objVal==0){
				    tablesColRelationsMapper.deleteByTableId(tablesVo.getTables().getTableId());
				    tablesMapper.deleteByPrimaryKey(tablesVo.getTables().getTableId());
				}
			}
		}
		return value;
	}
	
	/**
	 * 创建表
	 * @param tablesVo
	 * @return
	 */
	private int createTableSql(TablesVo tablesVo){
		int value= 0;
		try{
		if (null != tablesVo) {
			String columeName = "";
			String createSql = "";
			StringBuffer beforSb = new StringBuffer();
			StringBuffer afterSb = new StringBuffer();
			beforSb.append("CREATE TABLE `" + tablesVo.getTables().getTableName() + "` ("); 
			List<TablesColRelations> list = tablesVo.getTablesColRelations();
			for (TablesColRelations tablesColRelations : list) {
				beforSb.append("`" + tablesColRelations.getColumeName() + "` ").append(tablesColRelations.getColumeType());  
				if(tablesColRelations.getColumeLength() != null && tablesColRelations.getColumeLength() != 0 ){
					beforSb.append("(").append(tablesColRelations.getColumeLength());
				}
				if(tablesColRelations.getColumeXsdtf() !=null && tablesColRelations.getColumeXsdtf() != 0){
					beforSb.append(",").append(tablesColRelations.getColumeXsd());
				}
				if(tablesColRelations.getColumeLength() != null && tablesColRelations.getColumeLength() != 0){
					beforSb.append(")");
				}
				if(tablesColRelations.getPrimaryKey() == 1){
					columeName = tablesColRelations.getColumeName();
				}
			    if(tablesColRelations.getColumeNotNull() == 1){
				   beforSb.append(" NOT NULL,");
			    }else{
				   beforSb.append(" DEFAULT NULL,");
			    }			
			}
			if(StringUtils.isNotBlank(columeName)){	
				beforSb.append(createSql).append(" PRIMARY KEY (`").append(columeName).append("`)");
				afterSb.append(beforSb.toString());
			}else{
				createSql = beforSb.toString();
				createSql = createSql.substring(0,beforSb.lastIndexOf(","));
				afterSb.append(createSql);
			}
			afterSb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
			value = TablesUtils.executSql(afterSb.toString());
		  }
		}catch(Exception ex){
		    tablesColRelationsMapper.deleteByTableId(tablesVo.getTableId());
            tablesMapper.deleteByPrimaryKey(tablesVo.getTableId());
		}
		return value;
	}
	
	@Override
	public int updateTalbe(TablesVo record)throws Exception {
		int value= 0;
		if (null != record) {
			value = TablesUtils.dropTable(record.getTables().getTableName());
			if(value != -1){
			    List<TablesColRelations> list = record.getTablesColRelations();
	            if (null != list && list.size()>0) {
	                tablesColRelationsMapper.deleteByTableId(record.getTables().getTableId());
	                for (int i = 0; i < list.size(); i++) {
	                    TablesColRelations tablesColRelations = list.get(i);
	                    tablesColRelationsMapper.insertSelective(tablesColRelations);
	                }
	                value = tablesMapper.updateByPrimaryKeySelective(record.getTables());
	                int objVal = createTableSql(record);
	                if(objVal==0){
	                    tablesColRelationsMapper.deleteByTableId(record.getTables().getTableId());
	                    tablesMapper.deleteByPrimaryKey(record.getTables().getTableId());
	                }
	            }
			}			
		}
		return value;
	}

	@Override
	public Integer getTablesVal(String tableName) {
		return tablesMapper.getTablesVal(tableName);
	}

	@Override
	public Tables getTableByTableName(String tableName) {
		return tablesMapper.getTableByTableName(tableName);
	}
}
